<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>29、回调ref中执行次数的问题</title>
</head>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdn.staticfile.org/prop-types/15.6.1/prop-types.js"></script>

  <script type="text/babel">
    class Demo extends React.Component {
      render() {
        const { isHot } = this.state
        return (
          <div>
            {/* render在初始化的时候会执行一次，此时input的回调执行一次；当页面更新时，render也会执行，此时input的回调执行两次，第一次打印null，第二次打印input的dom节点 */}
            {/* 这是内联函数的写法，自执行 */}
            <input ref={ (currentNode) => { console.log(currentNode, '@') } } type="text" placeholder="点击右侧提示数据1" />&nbsp;
            {/* 将函数放在实例自身上，此时只有在初始化的时候会执行一次saveInput，页面更新的时候不会频繁触发了 */}
            <input ref={ this.saveInput } type="text" placeholder="点击右侧提示数据2" />&nbsp;
            <button onClick={ this.clickData }>点击提示左侧输入的数据</button>&nbsp;
            <p onClick={ this.changeWeather }>今天天气很{ isHot ? '炎热' : '凉爽' }</p>&nbsp;
          </div>
        )
      }

      state = { isHot: true }

      clickData = () => {
        alert(this.input1.value)
      }

      changeWeather = () => {
        const { isHot } = this.state
        this.setState({ isHot: !isHot })
      }

      saveInput = (c) => {
        console.log('实例自身上的函数走了几次')
        this.input1 = c
      }
    }
    ReactDOM.render(<Demo />, document.getElementById('test'))
  </script>
</body>
</html>